use std::cell::RefCell;
use std::rc::Rc;

use actix::ActorFutureExt;
use actix_http::body::EitherBody;
use actix_http::header::HeaderValue;
use actix_web::{Error, HttpResponse};
use actix_web::dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform};
use futures::FutureExt;
use futures::future::{LocalBoxFuture, ok, Ready, ready};
use crate::common::api_result::Api;

pub struct HandleMethod;

pub struct HandleMethodMiddleAware<S> {
    service: Rc<RefCell<S>>,
}

impl<S, B> Transform<S, ServiceRequest> for HandleMethod where
    S: Service<ServiceRequest, Response=ServiceResponse<B>, Error=Error> + 'static,
    S::Future: 'static,
    B: 'static
{
    type Response = ServiceResponse<EitherBody<B>>;
    type Error = Error;
    type Transform = HandleMethodMiddleAware<S>;
    type InitError = ();
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ready(Ok(HandleMethodMiddleAware {
            service: Rc::new(RefCell::new(service)),
        }))
    }
}

impl<S, B> Service<ServiceRequest> for HandleMethodMiddleAware<S> where
    S: Service<ServiceRequest, Response=ServiceResponse<B>, Error=Error> + 'static,
    S::Future: 'static,
    B: 'static,
{
    type Response = ServiceResponse<EitherBody<B>>;
    type Error = Error;
    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;

    forward_ready!(service);

    fn call(&self, req: ServiceRequest) -> Self::Future {
        println!("进入handle method");
        let service = self.service.clone();
        Box::pin(
            async move {
                let headers = req.headers();
                let option = headers.get("User-Agent");
                match option {
                    None => { service.call(req).await.map(|res| res.map_into_left_body()) }
                    Some(auth) => {
                        service.call(req).await.map(|res| res.map_into_left_body())
                    }
                }

            }.boxed_local()
        )
    }
}
